import os
from datetime import datetime, timedelta

from common.conf import Conf
from common.tools import Tool


class CanInvite:
    def __init__(self):
        self.conf = Conf()
        self.cli = self.conf.mongo_cli
        self.db = self.cli['项目']
        self.col = self.db["SIP_报文"]

    @property
    def root(self):
        if os.name == "nt": return "D://mygo/gb28181/test"
        return "/data/data/static/gb"

    def get_all_264(self, ssrc):
        res = []
        d = f"{self.root}/{ssrc}/h264"
        if not os.path.exists(d): return []
        for f in os.listdir(d):
            res.append(f"{d}/{f}")
        res.sort()
        return res

    def get_all_265(self, ssrc):
        res = []
        d = f"{self.root}/{ssrc}/h265"
        if not os.path.exists(d): return []
        for f in os.listdir(d):
            res.append(f"{d}/{f}")
        res.sort()
        return res

    def get_lates_stream(self, ssrc):
        l1 = self.get_all_264(ssrc)
        l2 = self.get_all_265(ssrc)
        res = l1 + l2
        if len(res) == 0:
            print("设备掉线", ssrc)
            return None
        res = [os.path.basename(p) for p in res]
        res = [f.split('.')[0] for f in res]
        res.sort()
        last = res[-1]
        return last

    def can_invite(self, camid, chanid):
        ssrc = Tool().from_camId_chanId_to_ssrc(camid, chanid)
        q = {"ty": "ssrc", "cam_id": camid, "chan_id": chanid, "ssrc": ssrc}
        res = self.col.find_one(q)
        if res is not None and res.get('invite_time', "") != "":
            diff = self.get_diff(res['invite_time'])
            if diff < 20:
                print("距离上次发送邀请", diff)
                return False

        now = datetime.now().strftime('%Y%m%d%H%M%S')
        d = {"invite_time": now}
        self.col.update_one(q, {"$set": d}, upsert=True)

        last = self.get_lates_stream(ssrc)
        print("last=====", last)
        if last is None:
            return True
        diff = self.get_diff(last)
        if diff < 60:
            print("距离最近的视频文件秒===", diff)
            return False
        return True

    def get_diff(self, last):
        last = datetime.strptime(last, '%Y%m%d%H%M%S')
        cur = datetime.now()
        print(cur, last)
        dif = timedelta.total_seconds(cur - last)
        return dif


if __name__ == '__main__':
    c = CanInvite()
